from src.laptop.predict.laptop_price_predict import LaptopPredictor
from src.laptop.preprocessor.model_data_preprocessor import process_predict_data
from src.utils.config import logger
import time
laptop_predictor = LaptopPredictor()


def process_laptop(data, reload=0):
    """
    处理笔记本数据
    :param data: 笔记本数据
    :param reload: 是否重新加载模型
    :return:
    """
    starttime = time.time()
    if reload == 1:
        laptop_predictor.load_models()
        return {'code': 0, 'message': 'reload success', 'results': []}

    res = process_predict_data(data,laptop_predictor.brand_fe, laptop_predictor.product_fe, laptop_predictor.median_dict, laptop_predictor.median_dict_temp)
    if res.empty:
        logger.error('data is empty after preprocess')
        return {'code': 1004, 'message': 'no data after preprocess', 'results': []}


    #530:F 10%  ,532:H,533:I  20%
    results_df = laptop_predictor.predict_price(res)
    results=results_df[['category', 'product_id', 'sku_id', 'price', 'level_id', 'brand_id',
                                        'is_new_product']].astype('object').to_dict('records')


    logger.info('inputdataSize={},outputdatasize={}, predict done data total elapsed time @{:.6f} s result={}'.format(len(data),len(res),time.time() - starttime,results))
    return {'code': 0, 'message': 'success', 'results': results}
